<template>
    <div class="section-container notice-container content-manage">
        <div class="section-title">{{route.meta.title}}</div>
        <el-tabs v-model="curState" @tab-change="handleTabChange">
            <el-tab-pane v-for="item in tabArr" :key="item.state" :label="item.name + '(' + item.count + ')'" :name="item.state" />
        </el-tabs>
        <div class="section-actions">
          <div class="actions-left">
              <el-button-group>
                  <el-button v-permission="['recruitment:admin:notice:add']" type="primary" @click="linkToAdd">发布公告</el-button>
                  <el-dropdown>
                  <el-button type="primary"><i class="iconfont">&#xe78d;</i></el-button>
                  <template #dropdown>
                      <el-dropdown-menu>
                      <el-dropdown-item><el-button @click="handleConditionSort">排序</el-button></el-dropdown-item>
                      <el-dropdown-item><el-button @click="handlePageSort">跨页暂存</el-button></el-dropdown-item>
                      <el-dropdown-item><el-button @click="archiveDialog = true">内容归档</el-button></el-dropdown-item>
                      </el-dropdown-menu>
                  </template>
                  </el-dropdown>
              </el-button-group>
              <SearchCmp ref="searchCmpRef" v-if="searchCmpArray.length" :searchCmpArray="searchCmpArray" :searchForm="queryData.likeParams" @onSubmit="handleSearch" />
          </div>
        </div>
        <div class="content-list">
            <!-- 表格样式 -->
            <ConditionSort v-model:show="showConditionSort" :orderFields="orderFields" @sort="handleSearch" />
            <PageSort ref="pageSortRef" v-model:show="showPageSort" @handleClear="handleSearch" />
            <div class="ruifox-list">
              <RuifoxTable
                :loading="tableLoading"
                v-model:tableData="newTableData"
                v-model:fieldList="fieldList"
                :canDrag="true"
                :default-index="true"
                :default-checkbox="true"
                :default-colum-config="true"
                :tableProps="tableProps"
                @handleSearch="handleSearch"
                @handleSort="handleSort"
              >
                <!-- 多选 -->
                <template #default-checkbox="{ element }">
                  <div class="table-div-check">
                    <el-checkbox class="unmover" v-model="element.checked" @change="handleCheckTable(element.id)" size="" />
                  </div>
                </template>
                <!-- 置顶 -->
                <template #is_top='{element}'>
                  <div class="table-td-top unmover">
                    <span v-permission="['']" :class="{'ding-yes': element.is_top,'ding-no': !element.is_top}" @click="handleTop(element)">顶</span>
                  </div>
                </template>
                <!-- 锁定 -->
                <template #is_lock="{ element }">
                  <el-tag type="danger" v-if="element.is_lock">已锁定</el-tag>
                  <el-tag type="success" v-else>未锁定</el-tag>
                </template>
                <!-- 发布用户 -->
                <template #publish_user_id="{ element }">
                  <span>{{ element.publish_user_name }}</span>
                </template>
                <!-- 标题缩略图 -->
                <template #thumb="{ element }">
                  <div class="table-td-title">
                    <div class="title-box">
                      <el-popover>
                        <template #reference>
                          <div class="thumb-box" style="max-width: 42px;height: 24px;" v-show="element.thumb">
                            <img :src="element.thumb" alt="" style="max-width: 100%;max-height: 100%">
                          </div>
                        </template>
                        <template #default>
                          <div class="thumb-box" style="max-width: 150px;max-height: 300px">
                            <img :src="element.thumb" alt="" style="width: 100%;height: 100%">
                          </div>
                        </template>
                      </el-popover>
                    </div>
                  </div>
                </template>
                <!-- url -->
                <template #url="{ element }">
                  <p v-html="element.url" :title="element.url"></p>
                </template>
                <!-- 状态 -->
                <template #state="{ element }">
                  <el-tag type="success">{{ element.state_message }}</el-tag>
                </template>
                <!-- 发布时间 -->
                <template #publish_time="{ element }"> {{ dayjs(element.publish_time).format('YYYY-MM-DD HH:mm') }}</template>
                <!-- 操作 -->
                <template #options="{ element }">
                  <div class="table-td-option unmover">
                    <el-button v-if="[99,1,3,5].includes(curState)" type="primary" link @click="handleEdit(element)" :disabled="!element.is_lock ? false : true">编辑</el-button>
                    <el-button v-if="[99].includes(curState)" type="primary" link @click="handleRevoke(element)" :disabled="!element.is_lock ? false : true">撤稿</el-button>
                    <el-dropdown>
                      <span class="el-dropdown-link">
                        <i class="iconfont">&#xe78d;</i>
                      </span>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item v-if="[99, 0, 1, 2, 3].includes(curState)" @click="handleTop(element)">
                              {{ element.is_top? '取消置顶' : '置顶' }}
                          </el-dropdown-item>
                          <el-dropdown-item v-if="[2].includes(curState)" @click="handleRecover(element)">恢复</el-dropdown-item>
                          <el-dropdown-item @click="handleViewFront(element)">前台浏览</el-dropdown-item>
                          <el-dropdown-item v-if="[5].includes(curState)" @click="handlePublish(element)">发布时间</el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </div>
                </template>
              </RuifoxTable>
            </div>
            <PaginationView
                :total="queryData.total"
                :pageSize="queryData.pageSize"
                :currentPage="queryData.currentPage"
                :allChoose="isAllChooseBtn"
                :pageChoose="isPageChooseBtn"
                :checkedNum="checkedNum"
                :options="curStateOptions"
                @changeSize="handleSizeChange"
                @currentChange="handleCurrentChange"
                @changePageChoose="handlePageChoose"
                @changeAllChoose="handleAllChoose"
                @cancelChoose="handleResetPagination"
                @invertChoose="handleInvertChoose"
                @refreshList="getTableData"
                @checkOption="handleBatch"
            />
            <!-- 内容选择弹框 -->
            <ContentChoose v-if="contentChooseShow" v-model:show="contentChooseShow" :searchCmpArray="searchCmpArray" :fieldList="fieldList" :orderFields="orderFields" :model="curModel"  @success="publishSuccess" />
            <!-- 归档时间选择 -->
            <el-dialog v-model="archiveDialog" title="内容归档" width="400px">
              <div class="archive-dialog-content">
                <p class="archive-tip">请选择归档时间点，系统将对该时间点之前的内容进行归档处理。</p>
                <p class="archive-warning">归档后的内容将不再在"已发布"列表中显示，可在"已归档"标签页中查看。</p>
                <div class="archive-time-picker">
                  <span class="label">归档时间：</span>
                  <el-date-picker v-model="archiveTime" type="datetime" placeholder="选择归档时间" format="YYYY-MM-DD HH:mm:ss" value-format="x" />
                </div>
              </div>
              <template #footer>
                <el-button @click="archiveDialog = false">取消</el-button>
                <el-button type="primary" @click="handleArchive">确认</el-button>
              </template>
            </el-dialog>
            <!-- 撤稿时间选择 -->
            <el-dialog v-model="revokeTimeDialog" title="撤稿时间选择" width="400px">
              <div class="archive-dialog-content">
                <p class="archive-tip">未选择撤稿时间即为立即撤稿。</p>
                <div class="archive-time-picker">
                  <span class="label">撤稿时间：</span>
                  <el-date-picker v-model="revokeTime" type="datetime" placeholder="选择撤稿时间" format="YYYY-MM-DD HH:mm:ss" value-format="x" />
                </div>
              </div>
              <template #footer>
                <el-button @click="revokeTimeDialog = false">取消</el-button>
                <el-button type="primary" @click="handleRevokeConfirm">确认</el-button>
              </template>
            </el-dialog>
          </div>
    </div>
</template>

<script setup>
import { reactive, ref, onMounted, computed, watch } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { tableList as mixTable, jumpRoute, hasPermission } from '@ruifox-cms/utils'
import { selectPage, selectStatesNum, updateWithdrawState } from '@/api/notice'
import { selectAllModel,selectAllField } from '@/api/model'
import ContentChoose from './components/ContentChoose.vue'
import ConditionSort from './components/ConditionSort.vue'
import PageSort from './components/PageSort.vue'
import { useRoute } from 'vue-router'
import dayjs from 'dayjs'

const route = useRoute()
// 分页逻辑局部混入
const {
  queryData,
  tableData,
  tableLoading,
  checkedNum,
  // isAllSearch,
  isAllChooseBtn,
  isPageChooseBtn,
  // checkedList,
  getTableData,
  handleSearch,
  handleCurrentChange,
  handleSizeChange,
  handlePageChoose,
  handleAllChoose,
  handleInvertChoose,
  handleCheckTable,
  handleResetPagination
} = mixTable({
  getListApi: selectPage
})

// 顶部tab及各状态可操作选项（注意添加state不要重复）
const curState = ref(99)
const curStateOptions = computed(() => {
  let result = []
  const options = tabArr.find(item => item.state == curState.value)?.options || []
  if(options.length > 0) {
    options.forEach(item => {
      if(!item.permission || hasPermission([item.permission])){
        result.push(item)
      }
    })
  }
  return result
})
const tabArr = reactive([
  {
    state: 99,
    name: '已发布',
    count: 0,
    options: [
      {name: '置顶', icon: '&#xe6f2;', value: 'batchTop', permission: ''},
      {name: '取消置顶', icon: '&#xe6f1;', value: 'batchCancelTop', permission: ''},
      {name: '撤稿', icon: '&#xe6e8;', value: 'batchRevoke', permission: ''},
    ]
  },
  {
    state: 5,
    name: '待发布',
    count: 0,
    options: [
      {name: '置顶', icon: '&#xe6f2;', value: 'batchTop', permission: ''},
      {name: '取消置顶', icon: '&#xe6f1;', value: 'batchCancelTop', permission: ''},
    ]
  },
  {
    state: 0,
    name: '审核中',
    count: 0,
    options: [
      {name: '置顶', icon: '&#xe6f2;', value: 'batchTop', permission: ''},
      {name: '取消置顶', icon: '&#xe6f1;', value: 'batchCancelTop', permission: ''},
    ]
  },
  {
    state: 2,
    name: '撤稿箱',
    count: 0,
    options: [
      {name: '置顶', icon: '&#xe6f2;', value: 'batchTop', permission: ''},
      {name: '取消置顶', icon: '&#xe6f1;', value: 'batchCancelTop', permission: ''},
      {name: '恢复', icon: '&#xe67b;', value: 'batchRecover', permission: ''}
    ]
  },
  {
    state: 3,
    name: '已退稿',
    count: 0,
    options: [
      {name: '置顶', icon: '&#xe6f2;', value: 'batchTop', permission: ''},
      {name: '取消置顶', icon: '&#xe6f1;', value: 'batchCancelTop', permission: ''},
    ]
  },
  {
    state: 4,
    name: '已归档',
    count: 0,
    options: [
      {name: '回档', icon: '&#xe6f2;', value: 'batchCancelPigeonhole', permission: ''}
    ]
  }
])
const _getContentStatistics = async () => {
  const res = await selectStatesNum()
  if (res.code === 20000) {
    tabArr.forEach(item => {
      item.count = res.data[item.state] || 0
    })
  }
}
_getContentStatistics()

// 归档数据查询
const getArchiveList = async () => {
  // const res = await selectPagePigeonhole(queryData)
  // if (res.code === 20000) {
  //   tableData.value = res.data.list
  //   queryData.total = res.data.total
  // }
}
const handleTabChange = val => {
  queryData.state = val
  handleResetPagination()
  if (val === 4) {
    getArchiveList()
  } else {
    getTableData()
  }
}

// 发布内容
const contentChooseShow = ref(false)
const linkToAdd = () => {
  contentChooseShow.value = true  
}

// tableData排除显示暂存区的内容
const newTableData = ref([])
watch(tableData, newVal => {
  if (showPageSort.value) {
    const sortIds = pageSortRef.value.tableData.map(item => item.id)
    newTableData.value = structuredClone(newVal)
    newTableData.value = newTableData.value.filter(item => !sortIds.includes(item.id))
  } else {
    newTableData.value = structuredClone(newVal)
  }
}, { deep: true })

// 获取当前模型信息
const modelId = ref(20)
const modelList = ref([])
const _getModelList = async () => {
  const res = await selectAllModel()
  if (res.code === 20000) {
    modelList.value = res.data
  }
}
const curModel = computed(() => modelList.value.find(item => item.id == modelId.value))

// 条件排序
const showConditionSort = ref(false)
const handleConditionSort = () => {
  showConditionSort.value = true
}
// 跨页暂存
const showPageSort = ref(false)
const pageSortRef = ref(null)
const handlePageSort = () => {
  if (showPageSort.value && pageSortRef.value.tableData.length > 0) {
    ElMessageBox.confirm(
      '当前暂存区还有内容，关闭后将还原内容到列表，是否继续？',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(() => {
      showPageSort.value = !showPageSort.value
      pageSortRef.value.tableData = []
    //   handleSearch()
    })
  } else {
    showPageSort.value = !showPageSort.value
  }
}
// 表头数据处理
const fieldList = ref([])
const orderFields = ref([]) // 排序字段
const tableProps = reactive({
  labelKey: 'name',
  valueKey: 'field'
})
//搜索
const searchCmpRef = ref(null)
const _getFieldList = async () => {
  tableLoading.value = true
  fieldList.value = []
  let res = await selectAllField({ modelId: curModel.value.id, enable: true })
  if (res.code === 20000) {
    orderFields.value = res.data.filter(item => item.isOrder)
    
    // 先添加置顶状态和收藏状态字段
    fieldList.value.push(
      { name: '', field: 'is_top', width: 30, fixed: 'left', showToUser: false, hideTitle: false },
      { name: '', field: 'is_collect', width: 30, fixed: 'left', showToUser: false, hideTitle: false }
    )

    // 处理其他字段
    let titleField = null
    res.data.forEach(item => {
      if (item.isShowControl || item.isShow) {
        item.show = item.isShow
        // 特殊处理字段
        switch(item.field) {
          case 'title':
            item.showTextTip = true
            item.width = 450
            item.fixed = 'left'
            titleField = item
            break
          case 'thumb':
            item.width = 30
            item.hideTitle = true
            break
          case 'url':
            item.showTipText = true
            item.width = 250
            break
          case 'create_time':
            item.width = 150
            break
        }
        // 字段选项禁用处理
        if (item.isShow && !item.isShowControl) {
          item.default = true
        }
        // 如果不是标题字段，直接添加到列表
        if (item.field !== 'title') {
          fieldList.value.push(item)
        }
      }
    })
    // 将标题字段插入到第三个位置
    if (titleField) {
      fieldList.value.splice(2, 0, titleField)
    }
    fieldList.value.push({ name: '发布时间', field: 'publish_time', width: 150, show: true, showToUser: true, default: true })
    fieldList.value.push({ name: '操作', field: 'options', width: 150, fixed: 'right', showToUser: false })
    handleDealSearchCmpArray()
  }
  tableLoading.value = false
}
// 可查询字段
const searchCmpArray = ref([])
const handleDealSearchCmpArray = () => {
  searchCmpArray.value = []
  fieldList.value.forEach(item => {
    if (item.isSearch) {
      let fieldObj = {
        key: item.field,
        label: item.name
      }
      fieldObj.form_type = fieldTypeMap[item.component]
      if (item.setting.options) {
        fieldObj.options = item.setting.options
      }

      searchCmpArray.value.push(fieldObj)
    }
  })
}
// 字段类型map
const fieldTypeMap = reactive({
  text: '',
  textarea: '',
  checkbox: 'multiple',
  select: 'select',
  selectMultiple: 'multiple',
  radio: 'select',
  datetime: 'datetime',
  number: 'count',
  title: '',
  summary: '',
  editor: '',
  depart: '',
  category: 'category'
})
// 内容列表查询参数
const defaultQueryData = reactive({
  currentPage: 1,
  pageSize: 10,
  state:99,
  likeParams: {},
  equalParams: {}
})
Object.assign(queryData, defaultQueryData)
// 归档
const archiveDialog = ref(false)
const archiveTime = ref('')
const handleArchive = async () => {
  // const data = {
  //   // catId: catId.value,
  //   time: archiveTime.value
  // }
  // const res = await pigeonhole(data)
  // if(res.code === 20000){
  //   ElMessage.success('归档成功')
  //   archiveDialog.value = false
  //   archiveTime.value = ''
  //   handleResetPagination()
  //   getTableData()
  //   _getContentStatistics()
  // }
}

/*************************************************************行操作*************************************/
// 编辑内容
const handleEdit = data => {
  if(curModel.value.procdefId){
    ElMessageBox.confirm('检测到当前栏目已绑定审核流，编辑后将使内容进入审核状态，是否继续？', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消'
    }).then(() => {
      jumpRoute('/resource/manage/setting', { modelId: curModel.value.id, publishType: curModel.value.publishType, folderId: 0, dataId: data.data_id }, '_blank')
    })
  } else {
    jumpRoute('/resource/manage/setting', { modelId: curModel.value.id, publishType: curModel.value.publishType, folderId: 0, dataId: data.data_id }, '_blank')
  }
}

// 撤稿
const revokeTimeDialog = ref(false)
const revokeTime = ref('')
const handleRevoke = data => {
  changeRow.value = data
  revokeTimeDialog.value = true
}
const handleRevokeConfirm = async () => {
  console.log(1234,revokeTime.value)
  let obj, res, msg
  if (revokeTime.value <= Date.now()) {
    obj = {
      dataIdList: [changeRow.value.id],
      state: 2,
      isAllChoose: false
    }
    res = await updateWithdrawState(obj)
    msg = '撤稿成功'
  } else {
    console.log(123,revokeTime.value)
    // obj = {
    //   catId: catId.value,
    //   dataId: changeRow.value.data_id,
    //   withdrawTime: revokeTime.value
    // }
    // res = await updateContentTiming(obj)
    // msg = '修改撤稿时间成功'
  }
  if (res.code === 20000) {
    ElMessage.success(msg)
    revokeTimeDialog.value = false
    revokeTime.value = ''
    getTableData()
    _getContentStatistics()
  }
}

// 发布时间修改
const changeRow = ref(null)

/***************************************************************批量操作**********************************/
const handleBatch = () => {

}

const publishSuccess = () => {
  getTableData()
  _getContentStatistics()
}

onMounted(async () => {
    await _getModelList()
    await _getFieldList()
  getTableData()
  window['updatePage'] = () => {
    getTableData()
    _getContentStatistics()
  }
})
</script>

<style lang="scss" scoped>
.content-manage {
    box-shadow: 0 0 5px rgba(#000, 0.1);
    .content-list {
    width: 100%;
    .ruifox-card-options {
        .ruifox-card-btn {
        i {
            margin-right: 5px;
        }
        }
    }
    .ruifox-list {
        .collect-btn i {
        color: #ccc;
        cursor: pointer;
        }
        .collect-btn.is-collect i {
        color: $mainColor;
        }
        .table-td-top{
        width: 18px;
        min-width: 18px;
        .ding-yes{
            display: inline-block;
            width: 16px;
            height: 16px;
            font-size: 12px;
            color: $white;
            line-height: 16px;
            text-align: center;
            background-color: #FF5240;
            cursor: pointer;
            margin-right: 5px;
        }
        .ding-yes:hover{
            background-color: #f78a7e;
        }
        .ding-no{
            display: inline-block;
            cursor: pointer;
            width: 16px;
            height: 16px;
            font-size: 12px;
            color: $white;
            line-height: 16px;
            text-align: center;
            background-color: #D7D7D7;
            margin-right: 5px;
            visibility: hidden;
        }
        .ding-no:hover{
            background-color: #817f7f;
        }
        }
        .table-td-title{
        display: flex;
        align-items: center;
        .title-tips{
            .iconfont{
            font-size: 14px;
            color: $mainColor;
            margin-right: 3px;
            }
            span{
            color: #aaa;
            margin-right: 20px;
            position: relative;
            }
            span+span:before{
            content: '|';
            position: absolute;
            left: -10px;
            top: -8px;
            }
        }
        .title-box{
            display: flex;
            justify-content: center;
            align-items: center;
            p{
            @include textEllipsis(16px,1)
            }
            .iconimg{
            display: inline-block;
            width: 16px;
            margin-right: 5px;
            i{
                color: #2CBF77;
                font-size: 15px;
            }
            }
            .a-icon{
            display: inline-block;
            width: 16px;
            background-color: $mainColor;
            color: $white;
            line-height: 16px;
            text-align: center;
            i{
                font-size: 14px;
            }
            }
            .p-icon{
            display: flex;
            align-items: center;
            width: 20px;
            color: #2CBF77;
            i{
                font-size: 18px;
            }
            }
            .thumb-box {
            display: flex;
            align-items: center;
            }
        }
        }
    }
    }
}
.button-box {
    padding-right: 10px;
    .el-button + .el-button {
    margin-left: 0;
    }
    flex-grow: 0;
    position: relative;
    i {
    position: absolute;
    right: -13px;
    top: 5px;
    color: $mainColor;
    cursor: pointer;
    }
}
.libarary-table {
    width: 100%;
    ::v-deep(.el-table__cell) {
    height: 50px;
    padding: 4px 0;
    }
    .option-btn {
    width: 35px;
    }
}
.archive-dialog-content {
    .archive-tip {
    font-size: 14px;
    color: #333;
    margin-bottom: 12px;
    }
    .archive-warning {
    font-size: 13px;
    color: #FF5240;
    margin-bottom: 20px;
    }
    .archive-time-picker {
    display: flex;
    align-items: center;
    .label {
        margin-right: 10px;
        color: #333;
    }
    }
}
</style>